const app = getApp()
const DBUtil = require('../lib/DBUtil')
const { UrlConfig, PATH, ACTION, DB } = require('./url')

const CONFIG_NAME = 'bill'
const DB_NAME = UrlConfig[CONFIG_NAME][DB]; //数据库名
const FILE_NAME = UrlConfig[CONFIG_NAME][PATH]  //云函数文件名

/**
 * [DB] 保存账单
 */
function saveBill(bill) {
  let options = {
    loading: '正在保存...',
    success: true,
    successText: '保存成功'
  }
  if (bill && bill._id) {
    // 更新
    return DBUtil.update(DB_NAME, bill, options)
  } else {
    // 插入
    return DBUtil.add(DB_NAME, bill, options)
  }
}

/**
 * [DB] 删除账单
 */
function deleteBill(id) {
  let options = {
    loading: '正在删除...',
    success: true,
    successText: '删除成功'
  }
  return DBUtil.remove(DB_NAME, id, options)
}

/**
 * [CLOUD] 查询收支
 * condition: 筛选条件，{page, size, begin, end, sort, direct, searchKey, filter}
 */
function getTotal(condition) {
  let action = UrlConfig[CONFIG_NAME][ACTION]['getTotal']
  return app.http(FILE_NAME, { action, ...condition })
}

/**
 * [CLOUD] 查询账单
 * condition: 筛选条件，{page, size, begin, end, sort, direct, searchKey, filter}
 */
function getPageBills(condition) {
  let options = {
    loading: '加载中...'
  }
  let action = UrlConfig[CONFIG_NAME][ACTION]['getPageBill']
  return app.http(FILE_NAME, { action, ...condition }, options)
}

/**
 * [CLOUD] 查询账单的类型
 * option: 筛选条件，{begin: '', end: ''}
 */
function getBillCategory(condition) {
  let options = {
    loading: '加载中...'
  }
  let action = UrlConfig[CONFIG_NAME][ACTION]['getBillCategory']
  return app.http(FILE_NAME, { action, ...condition }, options)
}

/**
 * [CLOUD] 更新category
 */
function updateCategory(condition) {
  let action = UrlConfig[CONFIG_NAME][ACTION]['updateCategory']
  return app.http(FILE_NAME, { action, ...condition })
}

/**
 * [CLOUD] 导出Excel
 */
function exportExcel(condition) {
  let action = UrlConfig[CONFIG_NAME][ACTION]['getExcel']
  return app.http(FILE_NAME, { action, ...condition })
}

/**
 * [调用云函数] 统计类别占比
 * condition: 筛选条件，{begin: '开始日期', end: '结束日期'}
 */
function getCateData(condition) {
  let options = {
    loading: '加载中...'
  }
  let action = UrlConfig[CONFIG_NAME][ACTION]['getCateData']
  return app.http(FILE_NAME, { action, ...condition }, options)
}

/**
 * [调用云函数] 统计月度收支
 * condition: 筛选条件，{begin: '开始日期', end: '结束日期'}
 */
function getMonthData(condition) {
  let options = {
    loading: '加载中...'
  }
  let action = UrlConfig[CONFIG_NAME][ACTION]['getMonthData']
  return app.http(FILE_NAME, { action, ...condition }, options)
}

module.exports = {
  saveBill: saveBill,
  getPageBills: getPageBills,
  getTotal: getTotal,
  getBillCategory: getBillCategory,
  deleteBill: deleteBill,
  exportExcel: exportExcel,
  updateCategory: updateCategory,
  getCateData: getCateData,
  getMonthData: getMonthData
}